﻿using Abp.Dependency;
using Abp.Runtime.Caching;
using Castle.Core.Logging;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace AbpProjectTemplate.Components.Notifications.SMS
{
    /// <summary>
    /// 聚合数据 短信API服务 https://www.juhe.cn/docs/api/id/54
    /// </summary>
    public class JHSmsSender : SmsSenderBase, ISmsSender
    {
        //private readonly IConfiguration _configuration;

        private readonly string _apiKey;
        private readonly string _mobileCodeTemplateId;
        public JHSmsSender(IConfiguration configuration)
        {
            //this._configuration = configuration;
            this._apiKey = configuration.GetSection("SMS:JH:ApiKey").Value;
            this._mobileCodeTemplateId = configuration.GetSection("SMS:JH:MobileCodeTemplateId").Value;
        }

        public async Task SendMobileCodeAsync(string mobile, string code)
        {
            this.SendCheck(mobile);

            var url = $"http://v.juhe.cn/sms/send?mobile={mobile}&tpl_id={this._mobileCodeTemplateId}&tpl_value=%23code%23%3D{code}&key={this._apiKey}";
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.GetAsync(url);
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        var json = JsonConvert.DeserializeObject<dynamic>(content);
                        if (json.error_code != 0)
                            throw new AppUserFriendlyException($"{json.error_code},{json.reason}");

                        await this.CacheSendAsync(mobile, code);
                    }
                }
                catch (Exception ex)
                {
                    this.Logger.Error("JHSmsHelper.SendMobileCodeAsync", ex);
                }
            }
        }
    }
}

